<template>
  <div class="departments">
    <el-card class="box-card">
      <!-- 第一行 -->
      <tree-tool :treeNode="company" :isRoot="true" @adddepart="getid" />

      <el-divider></el-divider>

      <el-tree
        :data="data"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <!-- 把data传递给这个组件里的treeNode -->
        <tree-tool
          slot-scope="{ data }"
          :treeNode="data"
          @adddepart="getid"
          @delSuccess="getDepartment"
          @editDepar="gotEdit"
        />
      </el-tree>
      <addDepart
        ref="editClick"
        :showDepats.sync="showAdd"
        :currtenId="currtID"
        @addsuce="getDepartment"
        @giveup="giveUp"
      ></addDepart>
    </el-card>
  </div>
</template>

<script>
// 导入组件
import treeTool from './components/tree'
import { getDepartments } from '@/api/departments'
import { toTree } from '@/utils'
import addDepart from './components/add-depatments'
export default {
  components: {
    treeTool,
    addDepart
  },
  data () {
    return {
      company: {
        name: '江苏传智播客教育科技股份有限公司',
        manager: '负责人'
      },
      // 绑定tree的默认显示文字和子节点
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      currtID: '',
      showAdd: false,
      // 默认数据
      data: []
    }
  },
  created () {
    this.getDepartment()
  },
  methods: {
    async getDepartment () {
      let res = await getDepartments()
      // console.log(res)
      this.company.name = res.data.companyName
      let list = res.data.depts
      // 调用
      let arr = toTree(list, '')
      // console.log(arr)
      this.data = arr
    },
    getid (id) {
      this.currtID = id
      this.showAdd = true
    },
    // 放弃修改
    giveUp () {
      this.showAdd = false
    },
    // 收到编辑事件通知
    async gotEdit (id) {
      await this.$refs.editClick.giteditmsg(id)
      this.showAdd = true
    }
  }
}
</script>

<style>
.box-card {
  margin: 20px;
  padding: 80px 60px;
}
</style>
